//
//  UITextView+Emoticon.swift
//  MyWeibo
//
//  Created by cat on 15/8/6.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit

extension UITextView {
    
    /// 插入表情符号
    func insertEmoticon(emoticon: Emoticon) {
        // emoji 字符串
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            
            return
        }
        // 表情图片
        if emoticon.chs != nil {
            // 创建图片属性字符串
            let attachment = EmotionAttachment()
            // 记录表情文字
            attachment.chs = emoticon.chs
            
            attachment.image = UIImage(contentsOfFile: emoticon.imagePath)
            
            let h = font!.lineHeight
            
            attachment.bounds = CGRect(x: 0, y: -4, width: h, height: h)
            
            let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            
            imageText.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
            
            // 图片插入到文本中
            let attrString = NSMutableAttributedString(attributedString: attributedText)
            
            attrString.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            
            let range = selectedRange
            attributedText = attrString
            selectedRange = NSRange(location: range.location + 1, length: 0)
        }
        
    }
    
    
    
    // 计算型属性
    var emoticonText: String {
        
        // 属性文本分段保存
        let attrString = attributedText
        var strM = String()
        
        attrString.enumerateAttributesInRange(NSMakeRange(0, attrString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) in
            if let attachment = dict["NSAttachment"] as? EmotionAttachment {
                strM += attachment.chs!
            } else {
                
                let str = (attrString.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        
        return strM
    }
}
